import { defineStore, Store } from 'pinia';
import { InjectionKey } from 'vue';
import { Tabs, TabsState } from './types';

const defaultTab = { path: '/dashboard/workplace', meta: { locale: '工作台' }, isDefault: true };

export const useTabsStore = defineStore('tabs', {

  state: (): TabsState => ({
    tabsList: []
  }),

  getters: {
    getTabs: (state) => {
      return state.tabsList;
    }
  },

  actions: {
    addTab(tab: Tabs) {
      if (this.tabsList && this.tabsList.some(item => item.path === tab.path)) return;
      this.tabsList && this.tabsList.length ? this.tabsList.push(tab) : this.tabsList = [defaultTab, tab]
    },
    removeTab(path: string) {
      const tabsList = this.tabsList
      const index = tabsList.findIndex(tab => tab.path === path);
      tabsList.splice(index, 1);
      return tabsList[index - 1];
    },
    saveTabs(status: any) {
      const tabsList = this.getTabs;
      const saveTabs = tabsList?.map(({ path, meta, name, isDefault }) => {
        return { path, meta, name, isDefault };
      });
      if (!status) saveTabs.length = 1;
      localStorage.setItem('tabsView', JSON.stringify(saveTabs));
    },
    loadTabs() {
      const oldTabs = localStorage.getItem('tabsView')
      if (!oldTabs) return;
      this.$patch({ tabsList: JSON.parse(oldTabs || "") })
    }
  },
});
